<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="modalTitle"
    :body-style="bodyStyle"
    @ok="onButtonOkClick"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, inject } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useUserStore } from '/@/store/modules/user';
  //获取当前登录用户项目编码
  const userStore = useUserStore();
  const currentProjectCode = userStore.getUserCurrentProjectCode;
  import { deptFormSchema } from './dept.data';
  import {
    getDept,
    addDept,
    updateDept,
    getProjectValidDept,
    getProjectValidDeptTree,
  } from '/@/api/project/dept';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'AddOrUpdateDept',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //弹出窗口界面是新增数据、修改数据；根据传递过来的参数进行判断
      const op = ref(OperationTypeEnum.UN_KNOWN);

      const dataId = ref('');

      const moduleName = inject<string>('moduleName');
      //标题--根据传入的模块名称+操作类型组合得到
      const modalTitle = ref('标题');

      const bodyStyle = {
        height: '400px',
        // overflow: 'hidden',
        // overflowY: 'scroll',
        // : body - style="bodyStyle"
      };

      const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
        labelWidth: 80,
        schemas: deptFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        getParentDept();
        console.log(data);
        //接收父组件传递的数据
        if (data?.op) {
          //判断是否传入op属性
          op.value = data.op;
        }

        if (data?.dataId) {
          dataId.value = data.dataId;
        }

        if (moduleName) {
          modalTitle.value = unref(moduleName);
        }
        if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        resetFields(); //重置表单
        setModalProps({ confirmLoading: false });

        //加载新增/修改中父级部门下拉列表
        // getProjectValidDepts();
        // 如果是修改数据，根据传入的id获取数据后进行赋值
        if (op.value == OperationTypeEnum.EDIT) {
          getDeptById();
        }
      });

      /**
       * 根据部门id获取部门详细信息，用于编辑回显
       */
      async function getDeptById() {
        // let flagOptions = [];
        // flagOptions.push({ label: '启用', value: '0' }, { label: '禁用', value: '5' });
        getDept(dataId.value)
          .then((res) => {
            console.log('res', res);
            setFieldsValue({
              ...res,
              parentid: res.parentid === 0 ? null : res.parentid,
              flag: Number(res.flag),
            });
            // updateSchema({
            //   field: 'flag',
            //   componentProps: {
            //     options: flagOptions,
            //   },
            // });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮，根据不同的op调用对应方法保存信息
       */
      async function onButtonOkClick() {
        //根据指定的操作类型分别进行提交数据和处理
        if (op.value == OperationTypeEnum.ADD) {
          //对应操作的步骤为：验证表单、提交后台保存、关闭modal、调用父组件事件刷新数据
          try {
            const values = await validate();
            setModalProps({ confirmLoading: true });
            //调用接口进行保存
            addDept(values)
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('保存成功。', 2);
                }
                opSuccess();
              })
              .catch((ex) => {
                console.log('catch ', ex);
                createMessage.error(ex.msg);
              });
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } else if (op.value == OperationTypeEnum.EDIT) {
          const values = await validate();
          console.log('修改的部门：', values.id);
          console.log('上级部门：', values.parentid);
          if (values.id == values.parentid) {
            createMessage.error('不能选择自己为上级部门', 5);
          } else {
            setModalProps({ confirmLoading: true });
            //调用接口进行保存
            updateDept(values)
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('修改成功。', 2);
                }
                opSuccess();
              })
              .catch((ex) => {
                console.log('catch ', ex);
                // createMessage.error(ex.msg);
              });
          }
        } else {
          createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
        }
      }

      /**
       * 获取项目有效部门，新增/修改时父级部门下拉列表
       */
      // function getProjectValidDepts() {
      //   //父级部门选项集合
      //   let deptOptions = [];
      //   if (op.value == OperationTypeEnum.EDIT) {
      //     deptOptions.push({ value: 0, label: '请选择' });
      //   }
      //   getProjectValidDept('')
      //     .then((res) => {
      //       console.log('res', res);
      //       res.forEach((dept) => {
      //         //options的value类型必须与表单中对应字段的类型一致，否则无法自动选中
      //         let deptId: number = dept.id as number;
      //         //根据层级在栏目名称前添加空格，实测空格无效，显示时没有空格
      //         let prefixSpaces = '';
      //         //修改中父级部门不选自己及下级部门
      //         if (op.value == OperationTypeEnum.EDIT) {
      //           if (dataId.value != dept.id) {
      //             if (dataId.value != dept.parentid) {
      //               for (let index = 0; index < dept.level; index++) {
      //                 prefixSpaces += '----';
      //               }
      //               deptOptions.push({ value: deptId, label: prefixSpaces + dept.name });
      //             }
      //           }
      //         } else {
      //           for (let index = 0; index < dept.level; index++) {
      //             prefixSpaces += '----';
      //           }
      //           deptOptions.push({ value: deptId, label: prefixSpaces + dept.name });
      //         }
      //       });

      //       //设置父级部门下拉列表
      //       updateSchema({
      //         field: 'parentid',
      //         componentProps: {
      //           options: deptOptions,
      //         },
      //       });
      //     })
      //     .catch((ex) => {
      //       console.log('catch ', ex);
      //       createMessage.error(ex.msg);
      //     });
      // }

      //操作成功后
      function opSuccess() {
        closeModal();
        emit('success');
      }
      function getParentDept() {
        getProjectValidDeptTree({ id: currentProjectCode })
          .then((res) => {
            console.log('res', res);
            updateSchema({
              field: 'parentid',
              componentProps: {
                treeData: res,
                fieldNames: { label: 'title', value: 'key', children: 'children' },
                treeDefaultExpandAll: true, //默认展开
                listHeight: 200, //设置弹窗滚动高度
              },
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }
      return {
        op,
        moduleName,
        modalTitle,
        getParentDept,
        registerModal,
        registerForm,
        onButtonOkClick,
        getDeptById,
        // getProjectValidDepts,
        opSuccess,
        bodyStyle,
      };
    },
  });
</script>
